package com.opensource.bykc.excel_lianxi.controller;


import com.opensource.bykc.excel_lianxi.utils.ExcelReportUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author wzh
 * @date 2024/9/16
 * @apiNote
 */
//
@RestController
@RequestMapping("/poi")
public class testControlller_poi {
    //   参考网页
    //https://segmentfault.com/a/1190000038566393

    /**
     * @description poi导出excel
     * @author wzh
     *
     */
    @GetMapping("/excel")
    public void test(){
        try {
            // 生成Excel路径
        String comFilePath = "H:\\project\\study\\面试demo\\机试题\\bykc\\springboot\\src\\main\\resources\\";
        String resultFileName = "result_01.xlsx";
        String resultFilePath = comFilePath + "file\\result\\"+resultFileName;
        String templatePath = comFilePath + "file\\template\\template_01.xlsx";
        ExcelReportUtil excelReportUtil = new ExcelReportUtil(templatePath);
            // 填充数据
            //Map<String, Object> map = new HashMap<>(64);
            //map.put("uname", "张三");
            //map.put("usex", "男");
            //map.put("ubirthday", "2020.10.01");
            //map.put("ucardid", "440582xxxxxxxx");
            //map.put("umarriage", "未婚");
            //map.put("unation", "汉族");
            //map.put("unative", "广东xxxx");
            //map.put("ubirthplace", "广东xxxx");
            //map.put("upolity", "团员");
            //map.put("uworktime", "2020.05.15");
            //map.put("uhealth", "良好");
            //或者封装成一个方法
            List<Map<String, Object>> maps = data1();
            for (int i = 0; i < maps.size(); i++) {

                //将excel文件数据写入到文件输出流
                Workbook workbook = excelReportUtil.filldata(maps.get(i));
                FileOutputStream fos = new FileOutputStream(resultFilePath);
                workbook.write(fos);
                fos.close();
                System.out.println("表生成成功！");

            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }


    /**
     * @description poi导出excel的zip文件
     * @author wzh
     *
     */
    //   添加到压缩包
    @GetMapping("/excel_zip")
    public void test(HttpServletRequest request, HttpServletResponse response){
        // 生成Excel路径
        String comFilePath = "H:\\project\\study\\面试demo\\机试题\\bykc\\springboot\\src\\main\\resources\\";

        String templatePath = comFilePath + "file\\template\\template_01.xlsx";
        OutputStream outputStream = null;
        ZipOutputStream out = null;
        String zipName = "郭德纲.zip";
        String browser = "";
        response.setContentType("application/octet-stream"); // 设置正确的MIME类型
        browser = request.getHeader("User-Agent");
        try {
            if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
                // IE6, IE7 浏览器
                response.addHeader("content-disposition", "attachment;filename="
                        + new String(zipName.getBytes(), "ISO8859-1"));
            } else if (-1 < browser.indexOf("MSIE 8.0")) {
                // IE8
                response.addHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(zipName, "UTF-8"));
            } else if (-1 < browser.indexOf("MSIE 9.0")) {
                // IE9
                response.addHeader("content-disposition", "attachment;filename="
                        + URLEncoder.encode(zipName, "UTF-8"));
            } else if (-1 < browser.indexOf("Chrome")) {
                // 谷歌
                response.addHeader("content-disposition",
                        "attachment;filename*=UTF-8''" + URLEncoder.encode(zipName, "UTF-8"));
            } else if (-1 < browser.indexOf("Safari")) {
                // 苹果
                response.addHeader("content-disposition", "attachment;filename="
                        + new String(zipName.getBytes(), "ISO8859-1"));
            } else {
                // 火狐或者其他的浏览器
                response.addHeader("content-disposition",
                        "attachment;filename*=UTF-8''" + URLEncoder.encode(zipName, "UTF-8"));
            }

            response.setCharacterEncoding("UTF-8");
            outputStream = response.getOutputStream();
            out = new ZipOutputStream(outputStream);
            ByteArrayOutputStream excelByteArrayOutputStream = new ByteArrayOutputStream();

            ExcelReportUtil excelReportUtil = new ExcelReportUtil(templatePath);
            List<Map<String, Object>> maps = data1();
            int j = zipName.lastIndexOf(".");
            String fileName = zipName.substring(0,j);
            for (int i = 0; i < maps.size(); i++) {

                //将excel文件数据写入到文件输出流
                Workbook workbook = excelReportUtil.filldata(maps.get(i));
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                workbook.write(byteArrayOutputStream);
                workbook.close(); // 关闭Workbook以释放资源
                // 添加ZipEntry并写入数据

                out.putNextEntry(new ZipEntry(fileName+"/"+"result\\result_02.xlsx"));
                //   下面这两行效果一样，二选一即可
                //excelByteArrayOutputStream.writeTo(out);
                out.write(byteArrayOutputStream.toByteArray());
                out.closeEntry();

                // 清理ByteArrayOutputStream
                byteArrayOutputStream.close();
            }
            System.out.println("表生成成功！");
            out.flush();
        }catch (IOException e){
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.finish();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }













    private List<Map<String,Object>> data1() {
        //   只能是一个map，两个map会报错，所有的东西写在一个map就行了
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map_01 = new HashMap<String,Object>();
        map_01.put("data1.ubegintime","2024");
        map_01.put("uname","王中华");
        list.add(map_01);
        //Map<String,Object> map_02 = new HashMap<String,Object>();
        //map_02.put("uname","王中华");
        //list.add(map_02);
        return list;
    }
}
